package com.umpay.service.consum.impl;


import java.util.List;

import com.umpay.utils.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;

import com.umpay.dao.online.TransDao;
import com.umpay.dao.online.consum.ConsumOrderOnlineDao;
import com.umpay.dao.online.consum.ConsumeOrderSubOnlineDao;
import com.umpay.dict.retcode.MerBusiEC;
import com.umpay.entity.Trans;
import com.umpay.entity.consum.ConsumOrder;
import com.umpay.entity.consum.ConsumOrderSub;
import com.umpay.exception.BusinessException;
import com.umpay.service.consum.ConsumeService;
import com.umpay.utils.TableNameHelper;

//@Service
public class ConsumeServiceImpl implements ConsumeService {

	private static final Logger log = LogManager.getLogger(ConsumeServiceImpl.class);
	
	@Autowired
	private ConsumOrderOnlineDao consumOrderOnlineDao;
	@Autowired
	private ConsumeOrderSubOnlineDao consumOrderSubOnlineDao;
	@Autowired
	private TransDao consumTransOnlineDao;
	@Autowired
	private TableNameHelper tableNameHelper;
	
	@Override
	public ConsumOrder findConsumeOrderOnline(ConsumOrder order) {
		log.info("【查询消费订单在线表请求参数】"+order);
		ConsumOrder consumOrder = null;
		try {
		    if(StringUtils.isNotEmpty(order.getOrderDate())) {
                tableNameHelper.generateTableName(order,order.getOrderDate());
            } else if (StringUtils.isNotEmpty(order.getTradeNo())) {
                tableNameHelper.getTableNameByTradeNo(order, order.getTradeNo());
            } else {
		        log.warn("没有可用的参数用来计算消费订单表表号");
            }
			consumOrder = consumOrderOnlineDao.find(order);
		} catch (DataAccessException e) {
			log.error("【查询消费订单在线表信息】查询ConsumeOrder失败",e);
		}
		log.info("【查询消费订单在线表响应结果】"+consumOrder);
		return consumOrder;
	}
	
	@Override
	public int update(ConsumOrder order) {
        setConsumeOrderTableName(order);
		int result = -1;
		log.info("【更新消费订单表信息开始】");
		try {
			log.info(String.format("更新消费订单状态及其他信息,:[%s]",order));
			result = consumOrderOnlineDao.update(order);
			log.info(String.format("更新消费订单表结束，结果result=[%s]",result));
			if(result != 1){
				throw new BusinessException(MerBusiEC.DB_ERROR,"更新消费订单表异常");
			}
		} catch (DataAccessException e) {
			log.error("【更新消费订单表】更新ConsumOrder失败",e);
			throw new BusinessException(MerBusiEC.DB_ERROR,"更新消费订单表失败");
		} catch(Exception e){
			log.error("【更新消费订单表】更新ConsumOrder失败",e);
			throw new BusinessException(MerBusiEC.DB_ERROR,"更新消费订单表失败");
		}
		log.info("【消费订单表信息结束】");
		return result;
	}
	@Override
	@Transactional
	public void insert(ConsumOrder consumOrder, List<ConsumOrderSub> list) {
		int orderResult = -1;
		int subOrderResult = -1;
		log.info("【插入消费订单表、子订单表】");
		try {
			log.info(String.format("【事务开启】插入消费订单表、子订单表:[%s][%s]", consumOrder, list));
			orderResult = consumOrderOnlineDao.insert(consumOrder);
			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					ConsumOrderSub consumOrderSub = list.get(i);
					subOrderResult = consumOrderSubOnlineDao.insert(consumOrderSub);
				}
			} else {
				log.info("插入消费订单表、子订单表，无子订单信息");
				subOrderResult = 1;
			}
			log.info(String.format("插入消费订单表、子订单表，结果orderResult=[%s],subOrderResult=[%s]",orderResult,subOrderResult));
		} catch (DataAccessException e) {
			log.error("【插入消费订单表、子订单表】插入失败",e);
			throw new BusinessException(MerBusiEC.DB_ERROR,"插入消费订单表、子订单表失败");
		} catch(Exception e){
			log.error("【插入消费订单表、子订单表】插入失败",e);
			throw new BusinessException(MerBusiEC.DB_ERROR,"插入消费订单表、子订单表失败");
		}
		log.info("【插入消费订单表、子订单表完成】");
	}

	@Override
	@Transactional
	public void insertConsumeOrderAndTrans(ConsumOrder consumOrder, List<ConsumOrderSub> subList, Trans trans)
			throws BusinessException {
		log.info("【插入消费订单表、子订单表和交易表】");
		try {
			log.info(String.format("【事务开启】插入消费订单表、子订单表:[%s][%s]", consumOrder, subList));
			insert(consumOrder,subList);
			consumTransOnlineDao.insert(trans);
		}catch (DataAccessException e) {
			if (e instanceof DuplicateKeyException) {
				//主键冲突异常
				log.info(String.format("插入数据表主键冲突"+trans));
				throw new BusinessException(MerBusiEC.ORDER_REPEAT,"商户支付流水重复");
			}
		    log.error("【插入绑卡订单表】插入数据库发生异常",e);
			throw new BusinessException(MerBusiEC.DB_ERROR,"数据库操作失败");
		}catch(Exception e){
			log.error("消费确认操作表失败",e);
			throw new BusinessException(MerBusiEC.SYSTEM_ERR,"系统发生错误！");
		}
	}
	
	/**
	 * description : 更新消费交易信息
	 * @author zhangru
	 * @date 2018年5月22日 上午10:16:22
	 * @version 1.0
	**/
	@Override
	public int updateConsumeTrans(Trans trans) throws BusinessException{
        setTransTableName(trans);
		int transResult = -1;
		log.info("【更新交易表信息开始】");
		try {
			log.info(String.format("更新消费交易信息,:[%s]",trans));
			transResult = consumTransOnlineDao.update(trans);
		} catch (DataAccessException e) {
			log.error("【更新交易表】更新失败",e);
			throw new BusinessException(MerBusiEC.DB_ERROR,"更新更新交易表失败");
		} catch(Exception e){
			log.error("【更新交易表】更新失败",e);
			throw new BusinessException(MerBusiEC.DB_ERROR,"更新更新交易表失败");
		} 
		if(transResult != 1){
			throw new BusinessException(MerBusiEC.DB_ERROR,"更新消费交易信息异常");
		}
		log.info("【更新交易表信息结束】");
		return transResult;
	}

	@Override
	public List<ConsumOrder> findList(ConsumOrder qryOrder) {
		log.info("【查询消费订单在线表请求参数】" + qryOrder);
		List<ConsumOrder> consumOrderList = null;
		try {
			consumOrderList = consumOrderOnlineDao.findList(qryOrder);
		} catch (DataAccessException e) {
			log.error("【查询消费订单在线表信息】查询ConsumeOrder失败",e);
		}
		log.info("【查询消费订单在线表响应结果】"+consumOrderList);
		return consumOrderList;
	}
	
	@Override
	public ConsumOrder findConsumeOrderOnlineByTradeNo(ConsumOrder order) {
		log.info("【查询消费订单在线表请求参数】"+order);
		ConsumOrder consumOrder = null;
		try {
			tableNameHelper.getTableNameByTradeNo(order,order.getTradeNo());
			consumOrder = consumOrderOnlineDao.find(order);
		} catch (DataAccessException e) {
			log.error("【查询消费订单在线表信息】查询ConsumeOrder失败",e);
		}
		log.info("【查询消费订单在线表响应结果】"+consumOrder);
		return consumOrder;
	}

    public void setConsumeOrderTableName(ConsumOrder order) {
        if(StringUtils.isNotEmpty(order.getOrderDate())) {
            tableNameHelper.generateTableName(order,order.getOrderDate());
        } else if (StringUtils.isNotEmpty(order.getTradeNo())) {
            tableNameHelper.getTableNameByTradeNo(order, order.getTradeNo());
        } else {
            log.warn("没有可用参数来计算消费订单表表号");
        }
    }


    public void setTransTableName(Trans trans) {
        if (StringUtils.isEmpty(trans.getTableName())) {
            tableNameHelper.getTableNameByTrace(trans, trans.getTrace());
        }
	}


}
